//
//  RecordHome_SignInSignOutCell.swift
//  mggz
//
//  Created by ShareAnimation on 2017/11/6.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText


class RecordHome_SignInSignOutCell: UITableViewCell {
    
    fileprivate lazy var caveLayer:CALayer = {
        let between : CGFloat = 1.0
        let radius = (12 - 2 * between)/3
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.frame = CGRect(x: 0, y: (12-radius)/2, width: radius, height: radius)
        shapeLayer.path = UIBezierPath.init(ovalIn: CGRect(x: 0, y: 0, width: radius, height: radius)).cgPath
        shapeLayer.fillColor = UIColor.init(red: 0.40, green: 0.40, blue: 0.40, alpha: 0.40).cgColor
        
      shapeLayer.add(YUReplicatorAnimation.scaleAnimation1(), forKey: "scaleAnimation")
      let replicatorLayer = CAReplicatorLayer.init()
      replicatorLayer.frame = CGRect(x: 0, y: 0, width: 12, height: 12)
      replicatorLayer.instanceDelay = 0.4
      replicatorLayer.instanceCount = 3
      replicatorLayer.instanceTransform = CATransform3DMakeTranslation(between * 2 + radius, 0, 0)
       replicatorLayer.addSublayer(shapeLayer)
       return replicatorLayer
    }()
    fileprivate lazy var foreverLayer : CABasicAnimation = {
        let animation = CABasicAnimation.init(keyPath: "opacity")
        animation.fromValue = NSNumber.init(value: 1.0)
        animation.toValue = NSNumber.init(value: 0.3)
        animation.autoreverses = true
        animation.duration = 0.4
        animation.repeatCount = HUGE
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
        animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn)
        return animation
    }()

    fileprivate lazy var stateImageView:UIImageView = {
        let iconView = UIImageView.init()
        iconView.image = UIImage(named: "Oval 12")
        return iconView
    }()
    fileprivate lazy var stateLabel:UILabel = {
        let label = UILabel.init()
        label.text = "未签到"
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = UIColor(red: 0.40, green: 0.40, blue: 0.40, alpha: 1)
        return label
    }()
    fileprivate lazy var caveView:UIView = {
        let view = UIView.init()
        view.isHidden = true
        return view
    }()
    var entryCover: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
        view.layer.cornerRadius = 50
        return view
    }()
    
    var entryButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        button.titleLabel?.numberOfLines = 2
        button.titleLabel?.textAlignment = .center
        button.layer.cornerRadius = 45
        button.layer.masksToBounds = true
        return button
    }()
    
    //cell下方的提示label
    fileprivate var recordState:String? = "进场"
    lazy var checkLocationLabel: YYLabel = {
        let label = YYLabel()
        
        let attributedText = NSMutableAttributedString(string: "当前不在签到范围内,")
    
        let imageView = UIImageView(image: UIImage.init(named: "警告"))
        imageView.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
        let attributedImage = NSAttributedString.yy_attachmentString(withContent: imageView, contentMode: .scaleAspectFit, attachmentSize: CGSize.init(width: 15, height: 15), alignTo: wwFont_Regular(12), alignment: .bottom)
        attributedText.insert(attributedImage, at: 0)
        
                let clickText = NSMutableAttributedString(string: "查看签到范围")
                clickText.yy_font = wwFont_Regular(12)
                clickText.yy_setTextHighlight(NSRange.init(location: 0, length: clickText.length), color: colorWith255RGB(16, g: 142, b: 233), backgroundColor: UIColor.lightGray){ (_, _, _, _) in
                    if self.checkLocationLabelTouchHandler != nil {
                        self.checkLocationLabelTouchHandler!()
                    }
                }
        
                attributedText.append(clickText)
        
        label.attributedText = attributedText
        return label
    }()
    
    // 签入按钮里的时间
    fileprivate var _entryTime: String!
    fileprivate var entryTime: String
    {
        set {
            let tempString = buttonContent(self.recordState!, time: newValue)
           // self.entryButton.setAttributedTitle(tempString, for: .normal)
            self.entryButton.setTitle(self.recordState, for: .normal)
        }
        get {
            if _entryTime !=  nil {
                return _entryTime
            }
            return "00:00:00"
        }
    }
    var mwWorkState : String = "z"{
        willSet {
            if newValue == "0"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = false
                self.stateImageView.isHidden = false
                self.stateLabel.text = "未签到"
                self.stateImageView.image = UIImage(named: "Oval 12")
            }else if newValue == "1"{
                self.stateLabel.isHidden = false
                self.caveView.isHidden = false
                self.caveView.layer.addSublayer(caveLayer)
                self.stateImageView.isHidden = false
                self.stateLabel.text = "务工中"
                self.stateImageView.image = UIImage(named: "Oval 22")
                
            }else if newValue == "2"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = false
                self.stateImageView.isHidden = false
                self.stateLabel.text = "暂离"
                self.stateImageView.image = UIImage(named: "Oval 2")
            }else if newValue == "3"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = false
                self.stateImageView.isHidden = false
                self.stateLabel.text = "已下班"
                self.stateImageView.image = UIImage(named: "Oval23")
                
            }else if newValue == "4"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = false
                self.stateImageView.isHidden = false
                self.stateLabel.text = "已下班(未考勤)"
                self.stateImageView.image = UIImage(named: "Oval23")
            }else if newValue == "5"{
                self.stateLabel.isHidden = false
                self.caveView.isHidden = false
                self.caveView.layer.addSublayer(caveLayer)
                self.stateImageView.isHidden = false
                self.stateLabel.text = "加班中"
                self.stateImageView.image = UIImage(named: "Oval 22")
            }else if newValue == "6"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = false
                self.stateImageView.isHidden = false
                self.stateLabel.text = "已下班(未记工)"
                self.stateImageView.image = UIImage(named: "Oval 2")
            }else if newValue == "z"{
                self.caveView.isHidden = true
                self.stateLabel.isHidden = true
                self.stateImageView.isHidden = true
            }
        }
    }
    
    var entryButtonEnable = false {
        willSet {
            self.entryButton.isEnabled = newValue
            if newValue {
                self.entryButton.isEnabled = true
                self.entryCover.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
                self.entryButton.backgroundColor = UIColor.mg_blue
            }
            else {
                
                self.entryTime = "00:00:00"
                self.entryButton.backgroundColor = UIColor.mg_noDataGray
                self.entryCover.backgroundColor = UIColor.mg_noDataGray.withAlphaComponent(0.3)
                self.entryButton.isEnabled = false
            }
        }
    }
    
    // cell是否有数据。
    var noData: Bool = true {
        willSet {
            if newValue {
                self.entryButtonEnable = false
            }
        }
    }
    
    //是否在签到范围
    var inRange = true {
        willSet {
            self.checkLocationLabel.isHidden = newValue
            if !newValue {
                self.entryButtonEnable = false
            }
        }
    }
    
    
    //签入签出按钮触发器
    var entryButtonTouchHandler:(() -> Void)?
    var exitButtonTouchHandler:(() -> Void)?
    
    //签到范围label点击处理器
    var checkLocationLabelTouchHandler:(() -> Void)?
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        self.setupViews()
        
        self.entryButton.addTarget(self, action: #selector(doEntryButtonAction), for: .touchUpInside)
        //self.exitButton.addTarget(self, action: #selector(doExitButtonAction), for: .touchUpInside)
        
        self.beginTimer()
        //初始化
//        self.noData = true
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupViews() {
        
        self.contentView.addSubview(self.stateImageView)
        self.stateImageView.snp.makeConstraints { (make) in
            make.top.equalTo(self.contentView).offset(10)
            make.left.equalTo(self.contentView).offset(20)
            make.width.height.equalTo(12)
        }
    
        self.contentView.addSubview(self.stateLabel)
        self.stateLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.stateImageView)
        make.left.equalTo(self.stateImageView.snp.right).offset(5)
            make.size.equalTo(CGSize(width: 90, height: 16))
        }
        self.contentView.addSubview(self.caveView)
        self.caveView.snp.makeConstraints { (make) in
        make.left.equalTo(self.stateLabel.snp.right).offset(-49)
            make.top.equalTo(self.contentView).offset(15)
            make.size.equalTo(CGSize(width: 11, height: 11))
        }
        
        self.contentView.addSubview(self.entryCover)
        self.entryCover.snp.makeConstraints { (make) in
            make.center.equalTo(self.contentView)
            make.width.height.equalTo(100)
        }
        
        self.entryCover.addSubview(entryButton)
        self.entryButton.snp.makeConstraints { (make) in
            make.center.equalTo(self.entryCover)
            make.width.height.equalTo(90)
        }
        
        self.checkLocationLabel.isHidden = true
        self.contentView.addSubview(checkLocationLabel)
        self.checkLocationLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.contentView)
        make.bottom.equalTo(self.contentView).offset(-10)
        }
    
    }
    
    
    //entryButton和exitButton的内容
    fileprivate func buttonContent(_ type: String, time: String) -> NSMutableAttributedString {
        let attributedText = NSMutableAttributedString(string: type + "\n",attributes: [NSAttributedStringKey.font:wwFont_Medium(17)])
        let timeText = NSAttributedString(string: time, attributes: [NSAttributedStringKey.font:wwFont_Medium(12)])
        attributedText.append(timeText)
    attributedText.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.white], range: NSRange.init(location: 0, length: attributedText.length))
        
        return attributedText
    }
    
    var timer:Timer?
    fileprivate func beginTimer() {
        if timer != nil {
            timer!.fireDate = Date()
            
            return
        }
        
        self.doTimerAction()
        self.timer = Timer(timeInterval: 1, target: self, selector: #selector(doTimerAction), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .commonModes)
    }
    
    fileprivate func stopTimer() {
        if self.timer != nil {
            self.timer!.fireDate = Date.distantFuture
        }
    }
    
    @objc func doTimerAction() {
        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm:ss"
        let dateString = formatter.string(from: date)
        
        if self.entryButtonEnable {
            self.entryTime = dateString
        }
        
        if self.mwWorkState == "0"{
   self.stateImageView.layer.add(self.foreverLayer, forKey: nil)
            
        }
       else if self.mwWorkState == "1"{
        
        }
    
    }
    
    fileprivate var isEntryAnimaiton = true
    @objc func doEntryButtonAction() {
        
        let scale = self.entryCover.bounds.width / self.entryButton.bounds.width
        let animaiton = AnimationTool.createRippleAnimation(scale: scale, duration: 0.1,delegate: self)
        self.entryButton.layer.add(animaiton, forKey: nil)
    }
    
//    @objc func doExitButtonAction() {
//        self.isEntryAnimaiton = false
//
//        let scale = self.exitCover.bounds.width / self.entryButton.bounds.width
//        let animaiton = AnimationTool.createRippleAnimation(scale: scale, duration: 0.5,delegate: self)
//        self.exitButton.layer.add(animaiton, forKey: nil)
//    }
    
    //MARK: 数据处理
    func bind(_ recordItems: [RecordModel]?) {
//        guard self.inRange else {
//            return
//        }
        //最后一条签到记录是签入，那么签入按钮变灰。否则签出变灰
        let item = recordItems?.last
        self.entryButtonEnable = true
        if item != nil  {
            if item?.signedType == .signedIn {
                
                self.recordState = "离场"
                let tempString = buttonContent("离场", time: self.entryTime)
                self.entryButton.backgroundColor = colorWith255RGB(247, g: 153, b: 146)
                self.entryCover.backgroundColor = colorWith255RGB(247, g: 153, b: 146).withAlphaComponent(0.3)
                self.isEntryAnimaiton = false
            self.entryButton.setTitle(self.recordState, for: .normal)
            }
            else {
                self.recordState = "进场"
            let tempString = buttonContent("进场", time: self.entryTime)
            self.entryCover.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
            self.entryButton.backgroundColor = UIColor.mg_blue
            self.isEntryAnimaiton = true
            //self.entryButton.setAttributedTitle(tempString, for: .normal)
                self.entryButton.setTitle(self.recordState, for: .normal)
            }
        }else{
            self.recordState = "进场"
            let tempString = buttonContent("进场", time: self.entryTime)
            self.entryCover.backgroundColor = UIColor.mg_blue.withAlphaComponent(0.3)
            self.entryButton.backgroundColor = UIColor.mg_blue
            self.isEntryAnimaiton = true
           // self.entryButton.setAttributedTitle(tempString, for: .normal)
            self.entryButton.setTitle(self.recordState, for: .normal)
        }
        
    }
}

extension RecordHome_SignInSignOutCell: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            
            if isEntryAnimaiton {
                if let entryHandler = self.entryButtonTouchHandler {
             self.entryButton.layer.removeAllAnimations()
                    entryHandler()
                }
            }
            else {
                if let exitHandler = self.exitButtonTouchHandler {
                self.entryButton.layer.removeAllAnimations()
                    exitHandler()
                }
            }
        }
        
    }
}










